//
//  SearchResultView.m
//  A段项目
//
//  Created by dllo on 16/1/29.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "SearchResultView.h"
#import "NetWorkingHandler.h"
#import "WaterFlowLayout.h"
#import "Model.h"
#import "HomePageCell.h"
#import <UIImageView+WebCache.h>
#import "SXLineLayout.h"
#import <MJRefresh.h>
#import "TouchFirstView.h"
#import <DKNightVersion.h>



@interface SearchResultView () <UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate,UICollectionViewDelegate,UICollectionViewDataSource,WaterFlowDelegate>

@property (nonatomic, retain) UISearchBar *search;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, copy) NSString *searchText; //记录输入的字符串.

@property (nonatomic, retain) NSMutableArray *arrDic;
@end

@implementation SearchResultView

{
    NSInteger num; //url 的刷新用.
    CGFloat contentOffsetY; //collection 的偏移量
        
    CGFloat oldContentOffsetY; //记录上一次的偏移量
    CGFloat newContentOffsetY; // 当前的偏移量
    
    BOOL selected; //搜索结果界面当前布局
    
}


- (void)dealloc {
    
    self.search.delegate = nil;
    
    self.tableView.delegate = nil;
    
    self.collectionView.delegate = nil;
    
    [_collectionView release];
    [_array release];
    [_search release];
    [_tableView release];
    [_searchText release];
    [_arrDic release];
    [super dealloc];
    
}

- (void)viewDidLoad {
    
    num = 1;
    [super viewDidLoad];
    
    [self createSearchBar];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           }];
    
    
    
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool1"];
    
    [_tableView release];
    
}

- (void)createSearchBar {
    
    self.search = [[UISearchBar alloc] init];
    [self.search becomeFirstResponder];
    self.search.delegate =self;
    self.search.layer.cornerRadius = 10;
    self.search.layer.masksToBounds = YES;
    self.search.text = @"";
    self.search.barTintColor = [UIColor lightGrayColor];
    self.search.tintColor = [UIColor lightGrayColor];
    
    self.search.barStyle = 1;
    self.search.searchBarStyle = 0;
    
    self.navigationItem.titleView = _search;
    
    self.navigationController.navigationBar.backItem.hidesBackButton = YES;
    
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:0 target:self action:@selector(cancalAction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self.navigationItem.rightBarButtonItem autorelease];
    
    [_search release];

    
}
/*点击取消. */
- (void)cancalAction{
    
    [_search endEditing:YES];
    
    [self.navigationController popViewControllerAnimated:YES];
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    
  cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    cell.textLabel.dk_textColorPicker =  DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
    NSString *text = [self.array objectAtIndex:indexPath.row];

    cell.textLabel.text = text;
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:cell.textLabel.text];
    
    NSStringCompareOptions mask = NSCaseInsensitiveSearch | NSNumericSearch;
    
    NSRange range = [cell.textLabel.text rangeOfString:self.searchText options:mask];
    
    
    [attri addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    
   
    [cell.textLabel setAttributedText:attri];
    
    [attri release];
    
    return cell;
    
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

  
    [self.array removeAllObjects];
    [self.collectionView removeFromSuperview];
    
    [self createTableView];
    
    self.searchText = [NSString stringWithString:searchBar.text];
    
    NSString *url = [[NSString stringWithFormat:@"http://api.tiankong.com/qjapi/searchtip/"]stringByAppendingString:searchBar.text];
    
    
    [NetWorkingHandler netWorkingWithUrl:url complete:^(id result) {
        
        
        self.array = [NSMutableArray arrayWithArray:result];
        
        [self.tableView reloadData];
        
    }];
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
  
    
    self.searchText = [NSString stringWithString:searchText];
    
    NSString *url = [[NSString stringWithFormat:@"http://api.tiankong.com/qjapi/searchtip/"]stringByAppendingString:searchText];
    
    
    [NetWorkingHandler netWorkingWithUrl:url complete:^(id result) {
       
       
        self.array = [NSMutableArray arrayWithArray:result];
        
        [self.tableView reloadData];
    
   }];
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.search endEditing:YES];
    
    NSString *str = [self.array objectAtIndex:indexPath.row];
    
    self.search.text = str;
    
    
      self.arrDic = [NSMutableArray array];
    
    NSString *url = [NSString stringWithFormat:@"http://mapp.tiankong.com/search?key=%@&pageNum=%ld&pageSize=50",self.search.text,num];
    
    
    __block typeof(self)weakSelf = self;
    [NetWorkingHandler netWorkingWithUrl:url complete:^(id result) {
        
        [weakSelf.array removeAllObjects];
        
        [weakSelf.tableView removeFromSuperview];
        
        [weakSelf createResultView];
        
        
        weakSelf.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           
            num ++;
            
        [weakSelf handleData];
            
            
        }];
        
        
        NSArray *arr = [result objectForKey:@"data"];
        
        self.arrDic = [NSMutableArray arrayWithArray:arr];
        
        for (NSDictionary *dic in arr) {
            
            
            
            Model *modle = [[Model alloc] init];
            
            [modle setValuesForKeysWithDictionary:dic];
            
            [self.array addObject:modle];
            
            [modle release];
        }
        
        [self.collectionView reloadData];
        
     
        
    }];
    
  
    
    
}


/**创建搜索结果显示界面. */

/**获取数据. */

- (void)handleData {

    
    NSString *url = [NSString stringWithFormat:@"http://mapp.tiankong.com/search?key=%@&pageNum=%ld&pageSize=50",self.search.text,num];
    
    [NetWorkingHandler netWorkingWithUrl:url complete:^(id result) {
        
        NSArray *arr = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in arr) {
            
            Model *modle = [[Model alloc] init];
            
            [modle setValuesForKeysWithDictionary:dic];
            
            [self.array addObject:modle];
            
            [modle release];
        }
        
        [self.collectionView reloadData];
        
      
        
    }];
    
    
}

#pragma marl 创建搜索结果显示界面
- (void)createResultView {
    
    WaterFlowLayout *flowLayout = [[WaterFlowLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    flowLayout.delegate = self;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 15)/2;
    
    flowLayout.itemSize =CGSizeMake(w, w);
    
    flowLayout.insertItemSpacing = 5;
    
    flowLayout.number = [NSNumber numberWithFloat:64];
    
    self.collectionView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    
    
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[HomePageCell class] forCellWithReuseIdentifier:@"pool1"];
    
    [flowLayout release];
    
  
    __block typeof(self)weakSelf = self;
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        num++;
        
        [weakSelf handleData];
    
    }];
    
    [_collectionView release];
    
}

/**collection协议方法. */

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    
   
    return self.array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HomePageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
    
    Model *model = [self.array objectAtIndex:indexPath.item];
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.url]];
    
       
    cell.backgroundColor = [UIColor redColor];
    
    return cell;
    
}

- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath {
    
    Model *model = [self.array objectAtIndex:indexPath.item];
    
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 15)/2;
    
    CGFloat height = (model.height/model.width) * w ;
    
    return height;

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [searchBar resignFirstResponder];
    
    NSString *url = [NSString stringWithFormat:@"http://mapp.tiankong.com/search?key=%@&pageNum=%ld&pageSize=50",searchBar.text,num];
    
    [self.array removeAllObjects];
    
    [self.tableView removeFromSuperview];
    
    [self createResultView];
    
   ;
    
    __block typeof(self)weakSelf = self;
    [NetWorkingHandler netWorkingWithUrl:url complete:^(id result) {
        
        NSArray *arr = [result objectForKey:@"data"];
        
        weakSelf.arrDic = [NSMutableArray arrayWithArray:arr];
        
        for (NSDictionary *dic in arr) {
            
            
            
            Model *modle = [[Model alloc] init];
            
            [modle setValuesForKeysWithDictionary:dic];
            
            [weakSelf.array addObject:modle];
            
            [modle release];
        }
        
        [weakSelf.collectionView reloadData];
        
        [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];

        
    }];

    
}


    
    


- (void)viewWillAppear:(BOOL)animated {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    

    
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    

    self.search.dk_tintColorPicker =  DKColorWithColors([UIColor whiteColor], [UIColor blackColor]);
    
    
        self.tabBarController.tabBar.hidden = YES; //隐藏 tabbar
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
   
        
        self.tabBarController.tabBar.hidden = NO;
        
   
    
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.collectionView) {
        
        newContentOffsetY = scrollView.contentOffset.y;
        
        /**当前位置的偏移量大于上一个位置是,表示 collection 向上滚动了.*/
        if (newContentOffsetY > oldContentOffsetY && newContentOffsetY> contentOffsetY) {
            
            self.navigationController.navigationBar.hidden = YES;
            
    
        }else {
            
        
            
            self.navigationController.navigationBar.hidden = NO;
            
        }
        
        
    }
    
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.collectionView) {
        
        contentOffsetY = scrollView.contentOffset.y; //记录初始偏移量.
        
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.collectionView) {
        
        oldContentOffsetY = scrollView.contentOffset.y;
        
        if (oldContentOffsetY <= 0) {
            
            self.navigationController.navigationBar.hidden = NO;
            
        }
        
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TouchFirstView *touch = [[TouchFirstView alloc] init];
    
    touch.array = [NSMutableArray arrayWithArray:self.arrDic];
    
    [self presentViewController:touch animated:NO completion:^{
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(touch.collectionView.bounds.size.width, 640);
        
        layout.scrollDirection = 1;
        layout.minimumInteritemSpacing =0;
        
        layout.minimumLineSpacing = 0;
        [touch.collectionView setCollectionViewLayout:layout];
      
        touch.collectionView.pagingEnabled = YES;
        
         touch.collectionView.contentOffset = CGPointMake(touch.collectionView.bounds.size.width * indexPath.item , 0);

        [touch.collectionView reloadData];
        
        [layout release];
    }];
    
    [touch release];
    
   
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
